package com.util;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by zjd
 * 集群，放行群集域和子域访问，使用Cookie保持记忆，单点登录
 */
public class CookieUtil {

    private final static String COOKIE_DOMAIN = ".taobao.com";
    private final static String COOKIE_NAME = "taobao_token";

    public CookieUtil() {

    }

    public static void writeCookieToken(HttpServletResponse response, String token) {
        Cookie ck = new Cookie(COOKIE_NAME, token);
//        ck.setDomain(COOKIE_DOMAIN);    生产环境打开此注释
        ck.setPath("/");//代表设置在根目录
        ck.setHttpOnly(true);//不允许黑客脚本攻击
        //如果这个MaxAge不设置的话，cookie就不会写入硬盘，而是写在内存。只在当前页面有效。
        ck.setMaxAge(Integer.MAX_VALUE);//如果是Integer.MAX_VALUE，代表永久保存，除非用户删除或重装系统，单位是秒。
        System.out.println("add cookieName:" + ck.getName() + ",cookieValue:" + ck.getValue());
        response.addCookie(ck);
    }

    public static String readCookieToken(HttpServletRequest request) {
        Cookie[] cks = request.getCookies();
        if (cks != null) {
            for (Cookie ck : cks) {
//                System.out.println("read cookieName:" + ck.getName() + ",cookieValue:" + ck.getValue());
                if (COOKIE_NAME.equals(ck.getName())) {
                    System.out.println("read cookieName:"+ck.getName()+",cookieValue:"+ck.getValue());
                    return ck.getValue();
                }
            }
        }
        return "TOKEN_SHARE";
    }


    public static void deleteToken(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cks = request.getCookies();
        if (cks != null) {
            for (Cookie ck : cks) {
                if (COOKIE_NAME.equals(ck.getName())) {
//                    ck.setDomain(COOKIE_DOMAIN);       生产环境打开此注释
                    ck.setPath("/");
                    ck.setMaxAge(0);//设置成0，代表删除此cookie。
                    System.out.println("delete cookieName:" + ck.getName() + ",cookieValue:" + ck.getValue());
                    response.addCookie(ck);
                    return;
                }
            }
        }
    }


}
